package org.jeecg.modules.outbound.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.outbound.entity.*;
import org.jeecg.modules.outbound.vo.BussProductOutboundOrderDetailVo;
import org.jeecg.modules.outbound.vo.BussProductOutboundOrderManagementPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.outbound.vo.BussProductOutboundOrderManagementPage;
import org.jeecg.modules.outbound.service.IBussProductOutboundOrderManagementService;
import org.jeecg.modules.outbound.service.IBussProductOutboundOrderInformationService;
import org.jeecg.modules.outbound.service.IBussProductOutboundOrderDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 成品出库单管理
 * @Author: jeecg-boot
 * @Date:   2024-07-17
 * @Version: V1.0
 */
@Api(tags="成品出库单管理")
@RestController
@RequestMapping("/outbound/bussProductOutboundOrderManagement")
@Slf4j
public class BussProductOutboundOrderManagementController {
	@Autowired
	private IBussProductOutboundOrderManagementService bussProductOutboundOrderManagementService;
	@Autowired
	private IBussProductOutboundOrderInformationService bussProductOutboundOrderInformationService;
	@Autowired
	private IBussProductOutboundOrderDetailService bussProductOutboundOrderDetailService;

	 /**
	  * 分页列表查询
	  *
	  * @param bussOutboundOrderManagement
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "出库单管理-分页列表查询")
	 @ApiOperation(value="出库单管理-分页列表查询", notes="出库单管理-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<BussProductOutboundOrderManagement>> queryPageList(BussProductOutboundOrderManagement bussOutboundOrderManagement,
																	 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																	 HttpServletRequest req) {
		 QueryWrapper<BussProductOutboundOrderManagement> queryWrapper = QueryGenerator.initQueryWrapper(bussOutboundOrderManagement, req.getParameterMap());
		 Page<BussProductOutboundOrderManagement> page = new Page<BussProductOutboundOrderManagement>(pageNo, pageSize);
		 IPage<BussProductOutboundOrderManagement> pageList = bussProductOutboundOrderManagementService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  *   添加
	  *
	  * @param bussOutboundOrderManagementPage
	  * @return
	  */
	 @AutoLog(value = "出库单管理-添加")
	 @ApiOperation(value="出库单管理-添加", notes="出库单管理-添加")
	 //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:add")
	 @PostMapping(value = "/add")
	 public Result<String> add(@RequestBody BussProductOutboundOrderManagementPage bussOutboundOrderManagementPage) {
		 BussProductOutboundOrderManagement bussOutboundOrderManagement = new BussProductOutboundOrderManagement();
		 BeanUtils.copyProperties(bussOutboundOrderManagementPage, bussOutboundOrderManagement);
		 bussProductOutboundOrderManagementService.saveMain(bussOutboundOrderManagement, bussOutboundOrderManagementPage.getBussOutboundOrderInformationList(),bussOutboundOrderManagementPage.getOutboundOrderDetailList());
		 return Result.OK("添加成功！");
	 }

	 /**
	  *  编辑
	  *
	  * @param bussOutboundOrderManagementPage
	  * @return
	  */
	 @AutoLog(value = "出库单管理-编辑")
	 @ApiOperation(value="出库单管理-编辑", notes="出库单管理-编辑")
	 //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:edit")
	 @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> edit(@RequestBody BussProductOutboundOrderManagementPage bussOutboundOrderManagementPage) {
		 BussProductOutboundOrderManagement bussOutboundOrderManagement = new BussProductOutboundOrderManagement();
		 BeanUtils.copyProperties(bussOutboundOrderManagementPage, bussOutboundOrderManagement);
		 BussProductOutboundOrderManagement bussOutboundOrderManagementEntity = bussProductOutboundOrderManagementService.getById(bussOutboundOrderManagement.getId());
		 if(bussOutboundOrderManagementEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 bussProductOutboundOrderManagementService.updateMain(bussOutboundOrderManagement, bussOutboundOrderManagementPage.getBussOutboundOrderInformationList(),bussOutboundOrderManagementPage.getOutboundOrderDetailList());
		 return Result.OK("编辑成功!");
	 }

	 /**
	  *   通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "出库单管理-通过id删除")
	 @ApiOperation(value="出库单管理-通过id删除", notes="出库单管理-通过id删除")
	 //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:delete")
	 @DeleteMapping(value = "/delete")
	 public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		 bussProductOutboundOrderManagementService.delMain(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  *  批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "出库单管理-批量删除")
	 @ApiOperation(value="出库单管理-批量删除", notes="出库单管理-批量删除")
	 //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:deleteBatch")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		 this.bussProductOutboundOrderManagementService.delBatchMain(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功！");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "出库单管理-通过id查询")
	 @ApiOperation(value="出库单管理-通过id查询", notes="出库单管理-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<BussProductOutboundOrderManagement> queryById(@RequestParam(name="id",required=true) String id) {
		 BussProductOutboundOrderManagement bussOutboundOrderManagement = bussProductOutboundOrderManagementService.getById(id);
		 if(bussOutboundOrderManagement==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(bussOutboundOrderManagement);

	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "出库单信息通过主表ID查询")
	 @ApiOperation(value="出库单信息主表ID查询", notes="出库单信息-通主表ID查询")
	 @GetMapping(value = "/queryBussProductOutboundOrderInformationByMainId")
	 public Result<List<BussProductOutboundOrderInformation>> queryBussProductOutboundOrderInformationListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<BussProductOutboundOrderInformation> bussOutboundOrderInformationList = bussProductOutboundOrderInformationService.selectByMainId(id);
		 return Result.OK(bussOutboundOrderInformationList);
	 }
	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "出库单明细通过主表ID查询")
	 @ApiOperation(value="出库单明细主表ID查询", notes="出库单明细-通主表ID查询")
	 @GetMapping(value = "/queryOutboundOrderDetailByMainId")
	 public Result<List<BussProductOutboundOrderDetailVo>> queryOutboundOrderDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<BussProductOutboundOrderDetailVo> outboundOrderDetailList =  bussProductOutboundOrderDetailService.selectByMainId(id);
		 return Result.OK(outboundOrderDetailList);
	 }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param bussOutboundOrderManagement
	  */
	 //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:exportXls")
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, BussProductOutboundOrderManagement bussOutboundOrderManagement) {
		 // Step.1 组装查询条件查询数据
		 QueryWrapper<BussProductOutboundOrderManagement> queryWrapper = QueryGenerator.initQueryWrapper(bussOutboundOrderManagement, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 //配置选中数据查询条件
		 String selections = request.getParameter("selections");
		 if(oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 queryWrapper.in("id",selectionList);
		 }
		 //Step.2 获取导出数据
		 List<BussProductOutboundOrderManagement> bussOutboundOrderManagementList = bussProductOutboundOrderManagementService.list(queryWrapper);

		 // Step.3 组装pageList
		 List<BussProductOutboundOrderManagementPage> pageList = new ArrayList<BussProductOutboundOrderManagementPage>();
		 for (BussProductOutboundOrderManagement main : bussOutboundOrderManagementList) {
			 BussProductOutboundOrderManagementPage vo = new BussProductOutboundOrderManagementPage();
			 BeanUtils.copyProperties(main, vo);
			 List<BussProductOutboundOrderInformation> bussOutboundOrderInformationList = bussProductOutboundOrderInformationService.selectByMainId(main.getId());
			 vo.setBussOutboundOrderInformationList(bussOutboundOrderInformationList);
			 List<BussProductOutboundOrderDetailVo> outboundOrderDetailList = new ArrayList<>();
			 //outboundOrderDetailService.selectByMainId(id);
			 vo.setOutboundOrderDetailList(outboundOrderDetailList);
			 pageList.add(vo);
		 }

		 // Step.4 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "出库单管理列表");
		 mv.addObject(NormalExcelConstants.CLASS, BussProductOutboundOrderManagementPage.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库单管理数据", "导出人:"+sysUser.getRealname(), "出库单管理"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 //@RequiresPermissions("org.jeecg.modules.demo:buss_outbound_order_management:importExcel")
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<BussProductOutboundOrderManagementPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BussProductOutboundOrderManagementPage.class, params);
				 for (BussProductOutboundOrderManagementPage page : list) {
					 BussProductOutboundOrderManagement po = new BussProductOutboundOrderManagement();
					 BeanUtils.copyProperties(page, po);
					 bussProductOutboundOrderManagementService.saveMain(po, page.getBussOutboundOrderInformationList(),page.getOutboundOrderDetailList());
				 }
				 return Result.OK("文件导入成功！数据行数:" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
				 return Result.error("文件导入失败:"+e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.OK("文件导入失败！");
	 }
	 @ApiOperation(value="根据id查询打印预览需要的数据", notes="根据id查询打印预览需要的数据")
	 @GetMapping(value = "/getPrintViewData/{id}")
	 public Result<List> getPrintViewData(@PathVariable("id") String id) {
		 ArrayList<Map<String, Object>> maps = new ArrayList<>();
		 Map<String, Object> map = new HashMap<>();
		 map.put("title","出库单");
		 map.put("templateId","978885860275281920");
		 map.put("id",id);
		 map.put("infoTable","buss_product_outbound_order_information");
		 map.put("table","buss_product_outbound_order_management");
//		 HashMap<String, Object> inMap = new HashMap<>();
//		 BussOutboundOrderManagement bussOutboundOrderManagement = bussOutboundOrderManagementService.selectForPrint(id);
//		 inMap.put("code",bussOutboundOrderManagement.getCode());
//		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//		 inMap.put("outboundDate",sdf.format(bussOutboundOrderManagement.getCreateTime()));
//		 inMap.put("nowDate",sdf.format(new Date()));
//		 inMap.put("createByName",bussOutboundOrderManagement.getCreateBy());
//		 inMap.put("warehouse",bussOutboundOrderManagement.getWarehouseId());
//		 inMap.put("remark",bussOutboundOrderManagement.getRemark());
//		 inMap.put("workshop",bussOutboundOrderManagement.getDepartmentWorkshop());
//		 inMap.put("outboundType",bussOutboundOrderManagement.getOutboundType());
//
//		 List<BussOutboundOrderDetail> outboundOrderDetailList =  bussOutboundOrderDetailService.selectForPrint(id);
//		 inMap.put("detail",outboundOrderDetailList);
//		 map.put("data",inMap);
		 maps.add(map);
		 return Result.OK(maps);
	 }

	 @GetMapping("/revokeBatch")
	 public Result<String> revokeBatch(@RequestParam(name="ids",required=true) String ids){
		 this.bussProductOutboundOrderManagementService.revokeBatch(Arrays.asList(ids.split(",")));
		 return Result.OK("撤销成功");
	 }
}
